//
//  WaiterDetailViewController.m
//  homeland
//
//  Created by caesar on 14-8-3.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "WaiterDetailViewController.h"
#import "ConsultPostViewController.h"
#import "EvaluateViewController.h"

@interface WaiterDetailViewController ()

@end

@implementation WaiterDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"社区服务网格员详情";
   
    [self getWaiterInfo];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

-(void)initView{
    
    if (self.entity && self.entity.imageUrl) {
        NSString *imageUrl = [NSString stringWithFormat:@"http://%@%@", SERVER_URL_COMMUNI_WAITER_IMAGE, self.entity.imageUrl];
//        NSString *imageUrl = [SERVER_URL_COMMUNI_WAITER_IMAGE stringByAppendingString:self.entity.imageUrl ];
        
        __block UIActivityIndicatorView *activityIndicator;
        __weak UIImageView *weakImageView = self.headImage;
        [self.headImage setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"waiter.png"] options:SDWebImageProgressiveDownload progress:^(NSUInteger receivedSize, long long expectedSize){
            if (!activityIndicator){
                [weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
                activityIndicator.center = weakImageView.center;
                [activityIndicator startAnimating];
            }
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType){
            [activityIndicator removeFromSuperview];
            activityIndicator = nil;
        }];
    }
    
    self.nameLable.text = self.entity.name;
    self.nationalityLable.text = self.entity.nationality;
    self.nation.text = self.entity.nation;
    self.phoneLable.text = self.entity.phone;
    self.infoTextView.text = self.entity.intro;
    
    
    //调整 位置
    CGFloat contentHeight = [self caculateHeightForString:self.infoTextView.text AndFontSize:14.0f AndWitdh:300.0f];
    
    self.infoTextView.frame = CGRectMake(10, CGRectGetMaxY(self.line.frame)+20 , 300, contentHeight);
    
    CGFloat totalHeight = MAX(CGRectGetMaxY(self.line.frame)+20, CGRectGetHeight(self.scrollView.frame));
    self.infoView.frame = CGRectMake(0.0, 0.0, 320.0, totalHeight+50);
    
    
    [self.scrollView addSubview: self.infoView];
     self.scrollView.contentSize = self.infoView.frame.size;
    [self.view addSubview:self.scrollView];
    
    float x = 106.66;
    NSArray *btnNameArr = @[@"咨询",@"电话",@"评价"];
    [self createBtn:0*x btnName:[btnNameArr objectAtIndex:0]  selector:@selector(consultEvent:)];
    [self createBtn:1*x btnName:[btnNameArr objectAtIndex:1]  selector:@selector(phoneEvent:)];
    [self createBtn:2*x btnName:[btnNameArr objectAtIndex:2]  selector:@selector(evaluateEvent:)];
}

//咨询事件
#pragma mark - consultEvent
-(void)consultEvent:(id)sender{
    if (_entity && _entity.Id) {
        ConfigableViewController *vc = [[ConsultPostViewController alloc]initWithNibName:@"ConsultPostViewController" bundle:nil];
        vc.config = @{@"uid": _entity.Id};
        [self.navigationController pushViewController:vc animated:YES];
    }
}
//电话事件
#pragma mark - phoneEvent
-(void)phoneEvent:(id)sender{
 
    if (self.entity && self.entity.phone) {
        [self isCallPhone:self.entity.phone];
    }
}
//评价事件
#pragma mark - evaluateEvent
-(void)evaluateEvent:(id)sender{
    EvaluateViewController *vc = [[EvaluateViewController alloc]initWithNibName:@"EvaluateViewController" bundle:nil];
    vc.config = @{@"uid": _entity.Id,@"name":_entity.name};
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)getWaiterInfo
{
    [self startLoadingViewWithText:@"正在载入..."];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    NSString *URL = [SERVER_URL_COMMUNITY_WAITER_ONE stringByAppendingFormat:@"%@",[self.config objectForKey:@"waiterId"]];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:URL  customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        
        [self stopLoadingView];
        NSDictionary *json = [completedOperation responseJSON];
        self.entity = getObjectFromDic([CommunityWaiterEntity class], json);
 
        [self initView];
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        [self stopLoadingView];
        [self.view makeToast:@"请求失败" duration:2.0 position:@"center"];
    }];
    [currentEngine enqueueOperation:op];
}

/**
 *创建提交按钮
 *@param btnType 创建的按钮类型：post提交按钮；end结束
 */
- (void)createBtn:(float)x  btnName:(NSString*)btnName selector:(SEL)selectorName {
    int height = iPhone5 ? 0 : 88 ;
    //生成底部按扭
    
    UIButton *postBtn = [[UIButton alloc] initWithFrame:CGRectMake(x,460 - height,106.66 , 44)];
    [postBtn setBackgroundImage:[UIImage imageNamed:@"btnImage.png"] forState:0];
    [postBtn setTitle:btnName forState:0];
    
    [postBtn addTarget:self action:selectorName forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:postBtn];
}

//是否拔号
-(void)isCallPhone:(NSString*)phone {
    if ([phone rangeOfString:@","].location != NSNotFound) {
        NSLog(@"准备截断电话号码%@",phone);
        phone = [phone substringToIndex:[phone rangeOfString:@","].location];
    }
    NSLog(@"点击了电话按钮%@",phone);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString  stringWithFormat:@"您是否需要拨打电话%@",phone] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = PHONE_ALERT_TAG;
    [alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == PHONE_ALERT_TAG) {
        if (buttonIndex == 1) {
           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",self.entity.phone]]];
        }
    }
}
@end
